<template>
  <div class="dialog-tree-use">
    <el-dialog :title="'选择栏目' + '-' + curModel.name" v-model="showDialog" width="960px" align-center>
      <div class="push-category-choose">
        <div class="push-category-btn">
          <div>
            <el-button type="primary" @click="showChooseDialog = true">选择栏目</el-button>
          </div>
        </div>
        <!-- 最近使用栏目 -->
        <div style="font-weight: 600">最近使用栏目</div>
        <div class="category-tree-box lasted-box">
          <div class="common-list" v-show="lastCategoryList.length > 0">
            <div class="common-item" v-for="item in lastCategoryList" :key="item.id" @click.prevent="handleTreeTitleCheck({ data: item, isLeaf: true })">
              <span class="title-text">{{ item.name }}</span>
              <div class="end-btns">
                <el-button class="end-btn" link>管理</el-button>
                <el-button class="end-btn" link @click.prevent="handleTreeCheck({ data: item })">发布</el-button>
              </div>
            </div>
          </div>
          <div class="no-data" v-show="lastCategoryList.length === 0">
            <i class="iconfont">&#xe642;</i>
            <p>暂无栏目信息，点击下方选择栏目</p>
            <el-button type="primary" @click="showChooseDialog = true">选择栏目</el-button>
          </div>
        </div>

        <!-- 栏目选择弹框 -->
        <el-dialog title="选择栏目" v-model="showChooseDialog" width="640px" align-center @open="handleOpenChooseDialog">
          <div class="category-tree-box" v-loading="categoryLoading">
            <el-scrollbar height="400px">
              <el-tree :data="categoryList" :props="treeProps" :check-on-click-node="true" node-key="id" class="tree-content">
                <template #default="{ node, data }">
                  <div class="tree-node-category" @click.prevent="handleTreeTitleCheck(node)">
                    <span class="title-text">{{ data.name }}</span>
                    <div class="end-btns">
                      <el-button class="end-btn" v-if="node.isLeaf" link>管理</el-button>
                      <el-button class="end-btn" v-if="node.isLeaf" link @click.prevent="handleTreeCheck(node)">发布</el-button>
                    </div>
                  </div>
                </template>
              </el-tree>
            </el-scrollbar>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showChooseDialog = false">取消</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, ref, computed } from 'vue'
import { createTreeData } from '@ruifox-cms/utils'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { getCategoryByModelId } from '@/api/category'

const props = defineProps({
  // 打开dialog
  showDialog: {
    type: Boolean,
    default: false
  },
  // 当前模块
  curModel: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const emit = defineEmits(['update:showDialog'])
const router = useRouter()
const store = useStore()
const showChooseDialog = ref(false)
const showDialog = computed({
  get() {
    return props.showDialog
  },
  set(val) {
    emit('update:showDialog', val)
  }
})
const curModel = computed(() => props.curModel)

// 点击标题
const handleTreeTitleCheck = node => {
  if (node.isLeaf) {
    router.push({
      path: '/content/manage',
      query: {
        catId: node.data.id,
        modelId: node.data.modelId,
        type: node.data.type
      }
    })
  }
}

// 点击发布
const handleTreeCheck = node => {
  // 保存到最近使用
  console.log('node', node)
  saveLastCategory(node.data)
  
  const toUrl = router.resolve({
    path: '/content/manage/setting',
    query: {
      modelId: curModel.value.id,
      catId: node.data.id,
      type: node.data.type,
      publishType: curModel.value.publishType
    }
  })
  window.open(toUrl.href, '_blank')
}

// 打开选择栏目弹框
const siteId = computed(() => store.state.site.currentSite?.id)
const categoryList = ref([])
const categoryLoading = ref(false)
const treeProps = ref({
  children: 'children',
  label: 'name'
})
const handleOpenChooseDialog = () => {
  categoryLoading.value = true
  getCategoryByModelId({ modelId: curModel.value.id, siteId: siteId.value }).then(res => {
    categoryList.value = createTreeData(res.data)
    categoryLoading.value = false
  })
}

// 保存最近使用栏目到 localStorage
const STORAGE_KEY = 'LAST_USED_CATEGORIES'
const MAX_LAST_CATEGORIES = 8
const saveLastCategory = (category) => {
  try {
    let lastCategories = getLastCategories()
    
    // 移除已存在的相同项
    lastCategories = lastCategories.filter(item => item.id !== category.id)
    
    // 添加到开头
    lastCategories.unshift({
      siteId: siteId.value,
      id: category.id,
      name: category.name,
      modelId: category.modelId,
      type: category.type
    })
    
    // 限制数量
    if (lastCategories.length > MAX_LAST_CATEGORIES) {
      lastCategories = lastCategories.slice(0, MAX_LAST_CATEGORIES)
    }
    
    localStorage.setItem(STORAGE_KEY, JSON.stringify(lastCategories))
    lastCategoryList.value = lastCategories
  } catch (e) {
    console.error('Failed to save last category:', e)
  }
}

// 从 localStorage 获取最近使用栏目
const getLastCategories = () => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    return stored ? JSON.parse(stored) : []
  } catch (e) {
    console.error('Failed to parse last categories:', e)
    return []
  }
}

const lastCategoryList = computed(() => {
  const data = getLastCategories()
  return data.filter(item => item.modelId === curModel.value.id && item.siteId === siteId.value)
})
</script>
<style lang="scss" scoped>
.dialog-tree-use {
  ::v-deep(.el-dialog) {
    & > .el-dialog__header {
      border-bottom: none;
    }

    & > .el-dialog__body {
      padding: 0 20px;
    }

    & > .el-dialog__footer {
      border-top: none;
    }
  }
}

.category-tree-box {
  margin-bottom: 10px;
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #e4e4e4;
  height: 400px;
  overflow: hidden;

  // 无数据状态
  .no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    i {
      font-size: 90px;
      color: #c9c7cf;
    }

    p {
      font-size: 14px;
      margin-bottom: 10px;
      color: #c9c7cf;
    }
  }

  // 树形结构
  .tree-content {
    height: 100%;
    overflow-y: auto;

    ::v-deep(.el-tree-node__label) {
      width: 100%;
    }

    ::v-deep(.el-tree-node__content) {
      height: 40px;
    }

    .tree-node-category {
      height: 40px;
      width: 100%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      padding: 0 20px 0 0;
      justify-content: space-between;

      .end-btn {
        display: none;
      }

      &:hover {
        .end-btn {
          display: block;
        }

        span {
          color: $mainColor;
          text-decoration: underline;
          cursor: pointer;
        }
      }
    }
  }

  // 常用列表
  .common-list {
    width: 100%;

    .common-item {
      height: 48px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e4e4e4;
      padding: 0 20px;
      cursor: pointer;

      .end-btn {
        display: none;
      }

      &:hover {
        .end-btn {
          display: block;
        }

        span {
          color: $mainColor;
          text-decoration: underline;
          cursor: pointer;
        }
      }
    }
  }
}

.lasted-box {
  display: block;
}

.push-category-btn {
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.end-btns {
  display: flex;
  justify-content: center;
}

.title-text {
  &:hover {
    color: $mainColor;
    text-decoration: underline;
    cursor: pointer;
  }
}
</style>
